<template>
  <main class="main">
    <div class="search">
      <input
        type="text"
        placeholder="请输入城市名称"
        v-model="searchKeywords"
        @input="handleInput"
      />
      <ul :class="{ invisible: !searchKeywords }">
        <p v-if="networkError">对不起网络似乎出了点问题 请稍后再查询</p>
        <p v-else-if="!searchCity">似乎没有找到你查找的城市</p>
        <li v-else @click="handleClick(searchCity, searchCityAdcode)">{{ searchCity }}</li>
      </ul>
    </div>
    <h2 v-if="localStorageData.length === 0">
      暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
    </h2>
    <div class="storage" v-else>
      <div class="city-storagy" v-for="item in localStorageData" :key="item.city">
        <div class="city-info">
          <h3>{{ item.city }}</h3>
          <span>{{ item.temperature }}度</span>
        </div>
        <div class="button-group">
          <button @click="handleClick(item.city, item.adcode)">查看</button>
          <button @click="deleteCity(item.city)">删除</button>
        </div>
      </div>
    </div>
    <h2 class="recent-weather">近期天气</h2>
    <slot></slot>
  </main>
</template>

<script setup>
import { ref } from 'vue';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';

import { useWeatherStore } from '@/stores/weatherStore';
import { getAdcodeByCity } from '@/api/index.js';

// 搜索关键词
const searchKeywords = ref('');
//控制网络错误元素的显示/隐藏
const networkError = ref(false);
const { searchCity, searchCityAdcode, localStorageData } = storeToRefs(useWeatherStore());
const router = useRouter();

const handleInput = async () => {
  // 如果用户输入的关键词长度小于2个字符时，直接返回，不执行后续的网络请求，提高用户输入体验。
  if (searchKeywords.value.length < 2) {
    searchCity.value = '';
    searchCityAdcode.value = '';
    return;
  } else {
    try {
      const { geocodes } = await getAdcodeByCity(searchKeywords.value);
      if (geocodes && geocodes.length > 0) {
        // 优先使用区县的名称
        if (geocodes[0].district && geocodes[0].district.length > 0) {
          searchCity.value = geocodes[0].district;
        } // 如果没有区县名称，使用城市名称
        else if (geocodes[0].city && geocodes[0].city.length > 0) {
          searchCity.value = geocodes[0].city;
        } // 如果没有城市名称，使用省份名称
        else if (geocodes[0].province && geocodes[0].province.length > 0) {
          searchCity.value = geocodes[0].province;
        }
        // 存储选中的城市的编码
        searchCityAdcode.value = geocodes[0].adcode || '';
      } else {
        // 如果 geocodes 为空，则清除 searchCity 和 searchCityAdcode
        searchCity.value = '';
        searchCityAdcode.value = '';
      }
      // 清除网络错误标志
      networkError.value = false;
    } catch (error) {
      console.error('获取城市编码时发生错误:', error);
      networkError.value = true;
      // 清除搜索城市
      searchCity.value = '';
      // 清除搜索城市编码
      searchCityAdcode.value = '';
    }
  }
};

const handleClick = async (city, adcode) => {
  if (adcode) {
    // 使用 adcode 作为路径参数，城市名称作为查询参数
    router.push({
      name: 'search', // 路由名称
      params: { adcode: adcode }, // 路径参数
      query: { search: city }, // 查询参数
    });
  }
};

const deleteCity = city => {
  const storedData = JSON.parse(localStorage.getItem('localStorageData'));
  // 删除存储数据中匹配的城市
  localStorageData.value = storedData.filter(item => item.city !== city);
  // 将新的数据存储到 localStorage 中
  localStorage.setItem('localStorageData', JSON.stringify(localStorageData.value));
};
</script>

<style lang="scss" scoped>
.invisible {
  display: none;
}

.main {
  color: #fff;
  padding-right: 10rem;
  padding-left: 10rem;

  .search {
    position: relative;
    padding-top: 1rem;
    margin-bottom: 2rem;

    input {
      width: 100%;
      padding-left: 0.25rem;
      padding-right: 0.25rem;
      padding-top: 0.5rem;
      padding-bottom: 0.5rem;
      background-color: transparent;
      border: none;
      border-bottom: 1px solid #e5e7eb;
      margin: 0;
      color: #fff;
      font-size: 100%;
      box-sizing: border-box;

      &:focus {
        border-bottom: 1px solid transparent;
        /* 焦点时边框颜色透明 */
        outline: none;
        /* 移除焦点时的轮廓 */
        box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
      }

      &::placeholder {
        color: #9ca3af;
      }
    }

    ul {
      position: absolute;
      top: 57px;
      display: block;
      width: 100%;
      margin: 0;
      background-color: #004e71;
      padding-left: 0.25rem;
      padding-right: 0.25rem;
      padding-top: 0.5rem;
      padding-bottom: 0.5rem;
      color: #fff;
      list-style: none;
      box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);

      p {
        margin: 0;
        display: block;
        line-height: 1.2rem;
      }

      p.invisible {
        display: none;
      }

      li {
        padding: 0.5rem 0;
        cursor: pointer;
      }
    }

    ul.invisible {
      display: none;
    }
  }

  h2 {
    text-align: center;
  }

  .storage {
    max-height: 300px;
    margin-top: 2.5rem;
    overflow: auto;

    &::-webkit-scrollbar {
      /* 隐藏滚动条 */
      display: none;
    }

    .city-storagy {
      display: flex;
      justify-content: space-between;

      &:hover {
        .city-info {
          width: 75%;
        }

        .button-group {
          button {
            display: block;
          }
        }
      }

      .city-info {
        display: flex;
        justify-content: space-between;
        width: 100%;
        background-color: #004e71;
        padding: 0.5rem 1rem;
        margin-bottom: 1rem;
        transition: all 0.3s;
        cursor: pointer;
        line-height: 1.5rem;

        h3 {
          margin: 0;
        }
      }

      .button-group {
        display: flex;
        gap: 0.5rem;
        margin-bottom: 1rem;

        button {
          display: none;
          height: 2.5rem;
          min-width: 5rem;
          padding: 0.5rem 1.5rem;
          background-color: #eab308;
          color: #fff;
          font-size: 1rem;
          text-align: center;
          line-height: 1.5rem;
          border: none;
          cursor: pointer;
        }
      }
    }
  }

  h2.recent-weather {
    margin: 0;
    margin-top: 1.5rem;
    text-align: left;
  }
}
</style>
